from fastapi import APIRouter, Query

from fastapiApp.controllers.menu_control import menu_controller
from fastapiApp.schemas.base_scheams import Fail, Success, SuccessExtra
from fastapiApp.schemas.menu_scheams import *

router = APIRouter()

@router.get("/get_list", summary="查看菜单列表")
async def list_menu(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量")
):
    async def get_menu_with_children(menu_id: int):
        menu = await menu_controller.model.get(id=menu_id)
        menu_dict = await menu.to_dict()
        child_menus = await menu_controller.model.filter(parent_id=menu_id).order_by("order")
        menu_dict["children"] = [await get_menu_with_children(child.id) for child in child_menus]
        return menu_dict

    parent_menus = await menu_controller.model.filter(parent_id=0).order_by("order")
    res_menu = [await get_menu_with_children(menu.id) for menu in parent_menus]
    return SuccessExtra(data=res_menu, total=len(res_menu), page=page, page_size=page_size)

@router.get("/get_info", summary="查看菜单")
async def get_menu(
    menu_id: int = Query(..., description="菜单id")
):
    menu_obj = await menu_controller.model.get(id=menu_id)
    data = await menu_obj.to_dict()
    return Success(data=data)

@router.post("/create", summary="创建菜单")
async def create_menu(menu_in: MenuCreate):
    await menu_controller.is_exist(obj_in = menu_in)
    await menu_controller.model.create(** menu_in.model_dump())
    return Success(msg="Created Successfully")

@router.post("/update", summary="更新菜单")
async def update_menu(
    obj_in: MenuUpdate
):
    await menu_controller.update_menu(obj_in=obj_in)
    return Success(msg=f"Update Successfully By ID = {obj_in.id}")

@router.delete("/delete", summary="删除菜单")
async def delete_menu(
    id: int = Query(..., description="菜单id")
):
    menu = await menu_controller.model.get_or_none(id = id)
    if menu:
        await menu.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")
